import React, { useState,useImperativeHandle,forwardRef, useEffect } from 'react'

import {get} from '@/utils'
import { Popup,Icon } from 'zarm';
import cx from 'classnames';

import s from './style.module.less';

const PopupType=forwardRef(({onSelect},ref)=>{

    const [show,setshow]=useState(false);
    const [active,setActive]=useState('all');
    const [expense,setExpense]=useState([]);  // 支出类型标签
    const [income,setIncome]=useState([]);  // 支出类型标签

    useEffect(async()=>{
        const {data:{list}}=await get('/api/type/list');
        // console.log(list);
        setExpense(list.filter(i=>i.type==2));
        setIncome(list.filter(i=>i.type==1));
    },[])

    useImperativeHandle(ref,()=>({
        setshow,
        active
    }))

    if (ref) {    // 挂载属性
        ref.current = {
          show: () => {
            setShow(true)
          },
          close: () => {
            setShow(false)
          }
        }
      }

    const choseType = (item)=>{
        setActive(item.id);
        setshow(false);
        onSelect(item)
    }

    return <Popup
    visible={show}
    onMaskClick={()=>setshow(false)}
    >
        <div className={s.popupType}>
            <div className={s.header}>
                请选择类型
                <Icon type="wrong" className={s.cross} onClick={()=>setshow(false)}></Icon>
            </div>
            <div className={s.content}>
                <div onClick={()=>choseType({id:'all'})} className={cx({[s.all]:true,[s.active]:active == 'all'})}>全部类型</div>
                <div className={s.title}>支出</div>
                <div className={s.expenseWrap}>
                    {
                        expense.map((item,index)=><p onClick={()=>choseType(item)} key={index} className={cx({[s.active]:active == item.id})}>{item.name}</p>)
                    }
                </div>

                <div className={s.title}>收入</div>
                <div className={s.incomeWrap}>
                    {
                        income.map((item,index)=><p  onClick={()=>choseType(item)} key={index} className={cx({[s.active]:active == item.id})}>{item.name}</p>)
                    }
                </div>
            </div>
        </div>
    </Popup>
})

export default PopupType;